<!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script crossorigin="anonymous" src="https://unpkg.com/@babel/standalone@7.8.7/babel.min.js"></script>
    <script crossorigin="anonymous" src="https://unpkg.com/react@16.8.6/umd/react.development.js"></script>
    <script crossorigin="anonymous" src="https://unpkg.com/react-dom@16.8.6/umd/react-dom.development.js"></script>
    <script crossorigin="anonymous" src="/test-harness.js"></script>
    <script crossorigin="anonymous" src="/test-page-object.js"></script>
    <script crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
    <style type="text/css">
      .test-harness {
        display: flex;
        flex-direction: column;
        height: 100%;
      }

      .test-harness__form {
        background-color: #ddd;
        border: solid 2px #ccc;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans',
          'Helvetica Neue', sans-serif;
        margin: 5px;
        padding: 5px;
      }

      body.jest .test-harness__form {
        display: none;
      }

      .test-harness__form-row {
        padding: 2px;
      }

      .test_harness__input {
        margin-right: 0.5em;
      }

      .test-harness__webchat {
        flex: 1;
      }
    </style>
  </head>
  <body>
    <main id="webchat"></main>
    <script type="text/babel" data-presets="env,stage-3,react">
      const {
        React: { useCallback, useEffect, useMemo, useState },
        ReactDOM: { render },
        WebChat: { ReactWebChat }
      } = window;

      const params = new URLSearchParams(window.location.hash.replace(/^#/u, ''));
      const initialDirection = params.get('dir');
      const initialFewerItems = !!params.get('fewer');
      const initialPreset = params.get('preset');

      const initialDisabled = params.get('disabled') === 'true' || /-disabled$/.test(initialPreset);

      const RadioRow = ({ checked, onChange, label, value }) => (
        <div className="test-harness__form-row">
          <label>
            <input checked={checked} className="test_harness__input" onChange={onChange} type="radio" value={value} />
            {label}
          </label>
        </div>
      );

      const STYLE_OPTIONS_PRESETS = {
        carousel: { suggestedActionLayout: 'carousel' },
        flow: { suggestedActionLayout: 'flow' },
        'flow-maxheight': { suggestedActionLayout: 'flow', suggestedActionsFlowMaxHeight: 120 },
        stacked: { suggestedActionLayout: 'stacked' },
        'stacked-disabled': { disabled: true, suggestedActionLayout: 'stacked' },
        'stacked-maxheight': { suggestedActionLayout: 'stacked', suggestedActionsStackedHeight: 120 }
      };

      const TestHarness = () => {
        const [direction, setDirection] = useState(() => initialDirection);
        const [disabled, setDisabled] = useState(() => initialDisabled || false);
        const [fewerItems, setFewerItems] = useState(() => initialFewerItems || false);
        const [preset, setPreset] = useState(() => initialPreset || 'carousel');

        const directLine = useMemo(
          () =>
            testHelpers.createDirectLineWithTranscript([
              {
                text: `Using preset \`${initialPreset}\` ${initialDirection === 'rtl' ? '(RTL)' : ''}`,
                type: 'message',
                id: 'CONVERSATION_ID-o|00000',
                timestamp: '2000-01-23T12:34:56.12345Z',
                channelId: 'directline',
                from: {
                  id: 'webchat-mockbot',
                  name: 'webchat-mockbot'
                },
                conversation: {
                  id: 'CONVERSATION_ID-o'
                },
                locale: 'en-US',
                suggestedActions: {
                  to: [],
                  actions: [
                    ...[
                      {
                        type: 'imBack',
                        title: 'A',
                        value: 'postback imback-string'
                      },
                      {
                        type: 'postBack',
                        title: 'B',
                        image:
                          '',
                        imageAltText: 'a red square',
                        value: 'postback postback-string'
                      },
                      {
                        type: 'postBack',
                        title: 'C',
                        image:
                          '',
                        imageAltText: 'a green rectangle',
                        text: 'Some text',
                        value: { hello: 'World!' }
                      }
                    ],
                    ...(fewerItems
                      ? []
                      : [
                          {
                            type: 'messageBack',
                            title: 'Et cillum pariatur cillum exercitation anim voluptate.',
                            image:
                              '',
                            imageAltText: 'a blue rectangle',
                            text: 'Some text',
                            displayText: 'say Hello World!',
                            value: { hello: 'World!' }
                          },
                          {
                            type: 'messageBack',
                            title: 'Consequat aute non exercitation do irure in adipisicing id dolor irure.',
                            image:
                              '',
                            imageAltText: 'a purple square',
                            value: { hello: 'World!' }
                          },
                          {
                            type: 'messageBack',
                            title: 'Aliquip et eiusmod aute ut dolor.',
                            image:
                              '',
                            imageAltText: 'a yellow square',
                            text: 'echo Hello',
                            displayText: 'Aloha'
                          }
                        ])
                  ]
                }
              }
            ]),
          [fewerItems]
        );

        const handleDisabledChange = useCallback(({ target: { checked } }) => setDisabled(checked), [setDisabled]);

        const handleDirectionChange = useCallback(
          ({ target: { checked } }) => setDirection(checked ? 'rtl' : undefined),
          [setDirection]
        );

        const handleFewerItemsChange = useCallback(
          ({ target: { checked } }) => setFewerItems(checked),
          [setFewerItems]
        );

        const handlePresetChange = useCallback(
          ({ target: { value } }) => {
            setPreset(value);
          },
          [setPreset]
        );

        useEffect(() => {
          const hashParams = new URLSearchParams({ preset });

          direction === 'rtl' && hashParams.set('dir', 'rtl');
          disabled && hashParams.set('disabled', 'true');
          fewerItems && hashParams.set('fewer', '1');

          window.history.replaceState(undefined, undefined, `#${hashParams}`);
        }, [direction, disabled, fewerItems, preset]);

        return (
          <div className="test-harness">
            <form className="test-harness__form">
              <RadioRow
                checked={preset === 'carousel'}
                onChange={handlePresetChange}
                label="Carousel"
                value="carousel"
              />
              <RadioRow checked={preset === 'flow'} onChange={handlePresetChange} label="Flow" value="flow" />
              <RadioRow
                checked={preset === 'flow-maxheight'}
                onChange={handlePresetChange}
                label="Flow with maxHeight"
                value="flow-maxheight"
              />
              <RadioRow checked={preset === 'stacked'} onChange={handlePresetChange} label="Stacked" value="stacked" />
              <RadioRow
                checked={preset === 'stacked-disabled'}
                onChange={handlePresetChange}
                label="Stacked and disabled"
                value="stacked-disabled"
              />
              <RadioRow
                checked={preset === 'stacked-maxheight'}
                onChange={handlePresetChange}
                label="Stacked with maxHeight"
                value="stacked-maxheight"
              />
              <hr />
              <div className="test-harness__form-row">
                <label>
                  <input
                    checked={fewerItems}
                    className="test_harness__input"
                    onChange={handleFewerItemsChange}
                    type="checkbox"
                  />
                  Fewer items
                </label>
              </div>
              <div className="test-harness__form-row">
                <label>
                  <input
                    checked={direction === 'rtl'}
                    className="test_harness__input"
                    onChange={handleDirectionChange}
                    type="checkbox"
                  />
                  Right-to-left
                </label>
              </div>
              <div className="test-harness__form-row">
                <label>
                  <input
                    checked={disabled}
                    className="test_harness__input"
                    onChange={handleDisabledChange}
                    type="checkbox"
                  />
                  Disabled
                </label>
              </div>
            </form>
            <ReactWebChat
              className="test-harness__webchat"
              directLine={directLine}
              dir={direction === 'rtl' ? 'rtl' : undefined}
              disabled={disabled}
              store={testHelpers.createStore()}
              styleOptions={STYLE_OPTIONS_PRESETS[preset]}
            />
          </div>
        );
      };

      render(<TestHarness />, document.getElementById('webchat'));

      run(async function () {
        await pageConditions.uiConnected();

        await host.snapshot();

        if (initialPreset === 'carousel' && !initialFewerItems) {
          // In carousel mode, take extra screenshots at the far side of the carousel.

          const scrollLeftOrigin = document.querySelector('.react-film__filmstrip').scrollLeft;

          const endFlipper = document.querySelector(
            initialDirection === 'rtl' ? '.react-film__main__slider--left' : '.react-film__main__slider--right'
          );

          for (let count = 0; count < 5; count++) {
            await host.click(endFlipper);
          }

          // We need to wait for the scroll animation to complete before taking a screenshot.
          await testHelpers.sleep(1000);

          await host.snapshot();

          // We need to scroll it back, otherwise, we will not be able to click the first button.
          document.querySelector('.react-film__filmstrip').scrollLeft = scrollLeftOrigin;
        } else if (/-maxheight$/iu.test(initialPreset)) {
          // When maxHeight is set, take extra screenshots at the bottommost of the scrollable.

          const scrollable = document.querySelector(
            '.webchat__suggested-actions__flow-box, .webchat__suggested-actions__stack'
          );

          scrollable.scrollTop = scrollable.scrollHeight - scrollable.offsetHeight;

          await host.snapshot();
        }

        // Test clicking the button only if they are not disabled.
        if (!/-disabled$/iu.test(initialPreset)) {
          await pageObjects.clickNthSuggestedAction(1);
          await pageConditions.numActivitiesShown(2);
          await host.snapshot();
        }
      });
    </script>
  </body>
</html>
